<template>
  <div class="xh-user">
    <div class="xh-user__hd">
      {{ title }}
    </div>
    <div class="xh-user__bd">
      <el-autocomplete v-model="searchInput" :disabled="disabled" :fetch-suggestions="searchListUser"
                       placeholder="请输入内容" @select="searchSelect">
        <template v-slot:default="{ item }">
          <span>{{ item[userConfig.label] }}</span>
          <span style="color: #999;">{{
              `(${item.deptName || ''}${item.deptName ? '-' : ''}${item.post || '无'})`
            }}</span>
        </template>
      </el-autocomplete>
      <div v-loading="loading" class="search-list">
        <el-breadcrumb v-if="breadcrumbList.length > 0 && !config.isList"
                       style="padding: 5px 0;"
                       separator-class="el-icon-arrow-right">
          <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="index">
            <a href="javascript:;" @click="breadcrumbBtn(item, index)">{{ item.label }}</a>
          </el-breadcrumb-item>
        </el-breadcrumb>

        <div v-if="currentBreadcrumbItem" class="xh-user__list">
          <el-checkbox v-if="!radio" v-model="allChecked"
                       :disabled="disabled"
                       style="line-height: 30px;"
                       @change="handleCheckAllChange">全选
          </el-checkbox>
          <WkDepCheckbox ref="depCheckboxRef"
                         :class="`is-select-${config.selectType}`"
                         :radio="radio"
                         :data="currentBreadcrumbItem.deptList"
                         :props="depConfig"
                         v-model="depDataValue"
                         :disabled="disabled || config.selectType === 'user'"
                         @next="nextDebounceClick"
                         @change="depCheckboxChange"
                         @all-select="depAllSelect"></WkDepCheckbox>

          <WkUserCheckbox ref="userCheckboxRef"
                          :class="`is-select-${config.selectType}`"
                          :radio="radio"
                          :data="currentBreadcrumbItem.employeeList"
                          :props="userConfig"
                          v-model="userDataValue"
                          :disabled="disabled || config.selectType === 'dep'"
                          @change="userCheckboxChange"
                          @all-select="userAllSelect"></WkUserCheckbox>
        </div>

      </div>
    </div>
    <flexbox v-if="config.showFooter" class="xh-user__ft">
      <flexbox-item class="select-info">已选择<span
          class="select-info--num">{{ (depDataValue.length || 0) + (userDataValue.length || 0) }}</span>项
      </flexbox-item>
      <el-button link @click="clearAll">清空</el-button>
      <el-button v-if="config.showSureBtn" link @click="sureClick">确定</el-button>
    </flexbox>
  </div>
</template>

<script setup>

import WkDepCheckbox from '../../WkDepSelect/src/WkDepCheckbox.vue'
import WkUserCheckbox from '../../WkUserSelect/src/WkUserCheckbox.vue'
import {adminUserQueryByDeptAPI} from '/src/api/admin/user.js'
import {hrmEmployeeQueryByDeptAPI, hrmEmployeeQueryInAPI} from '/src/api/hrm/employee.js'
import {userListAPI} from '/src/api/common.js'


import PinyinMatch from 'pinyin-match'
import merge from '/src/utils/merge.js'
import {debounce} from 'throttle-debounce'
import {objDeepCopy} from '/src/utils/index.js'
// import { valueEquals } from 'element-ui/lib/utils/util'
import {valueEquals} from '/src/utils/elementui.js'


const DefaultWkUser = {
  value: 'userId',
  label: 'realname'
}


const DefaultWkDep = {
  value: 'deptId',
  label: 'name'
}

const DefaultWkUserDep = {
  // 树结构请求和参数
  request: null,
  params: null,
  // 默认的搜索人资和管理端人员请求
  // isHrm: false, // 替换为 dataType 默认 manage 其余 hrm
  dataType: 'manage', // 默认管理端
  // userOptions: null, // 固定数据，后可以放入 props options
  isList: false, // 默认是树形接口，如果是列需设置为true
  showFooter: true, // 默认不隐藏，MembersDep 有数量条，需要隐藏
  showSureBtn: false, // 默认不展示按钮
  selectType: 'all' //  all user dep 全选  仅员工  仅部门
}

defineOptions({
  name: 'WkUserDep', // 新建 WkUserDep
  inheritAttrs: false,
})

const properties = defineProps({

  options: Array,
  radio: Boolean, // 未支持
  props: {
    type: Object,
    default: () => {
      return {}
    }
  },
  userProps: {
    type: Object,
    default: () => {
      return {}
    }
  },
  userValue: Array,
  depProps: {
    type: Object,
    default: () => {
      return {}
    }
  },
  depValue: Array,
  disabled: {
    type: Boolean,
    default: false
  }
})


const emits = defineEmits(
    ['update:userValue', 'update:depValue',
      'depChange', 'userChange',
      'change', 'close',])


const userCheckboxRef = ref();
const depCheckboxRef = ref();

const optionData = reactive({
  loading: false,
  searchInput: '',
  searchUserList: [],

  // 面包头
  breadcrumbList: [],

  // 当前面包屑
  currentBreadcrumbItem: null,
  // 全选
  allChecked: false,
  userAllChecked: false,
  depAllChecked: false,
  userDataValue: [],
  depDataValue: []
})

const {
  loading, searchInput, searchUserList, breadcrumbList,
  currentBreadcrumbItem, allChecked, userAllChecked, depAllChecked, userDataValue, depDataValue
} = toRefs(optionData)


const userConfig = computed(() => {
  return merge({...DefaultWkUser}, properties.userProps || {})
})

const depConfig = computed(() => {
  return merge({...DefaultWkDep}, properties.depProps || {})
})
const config = computed(() => {
  return merge({...DefaultWkUserDep}, properties.props || {})
})
const title = computed(() => {
  return {
    'all': '员工/部门',
    'user': '员工',
    'dep': '部门'
  }[config.value.selectType]
})

watch(breadcrumbList, () => {
  if (!config.value.isList) {
    optionData.currentBreadcrumbItem = optionData.breadcrumbList[optionData.breadcrumbList.length - 1]
  }
})

watch(() => properties.options, (val) => {
  if (config.value.isList) {
    optionData.currentBreadcrumbItem = {
      employeeList: properties.options
    }
  }
}, {
  immediate: true
})
watch(() => properties.userValue, () => {
  if (!valueEquals(properties.userValue, optionData.userDataValue)) {
    optionData.userDataValue = objDeepCopy(properties.userValue)
  }
}, {
  immediate: true
})
watch(() => properties.depValue, () => {
  if (!valueEquals(properties.depValue, optionData.depDataValue)) {
    optionData.depDataValue = objDeepCopy(properties.depValue)
  }
}, {
  immediate: true
})

let nextDebounceClick = () => {
}

function created() {
  if (!config.value.isList) {
    getDepUserList(0)
    nextDebounceClick = debounce(300, nextClick)
  } else {
    nextDebounceClick = () => {
    }
  }
}

created()


/**
 * 列效果进行搜索
 */
function searchListUser(queryString, cb) {
  if (optionData.searchUserList && optionData.searchUserList.length || properties.options) {
    const searchUserList = properties.options || optionData.searchUserList
    if (queryString) {
      cb(searchUserList.filter(item => PinyinMatch.match(item[userConfig.value.label] || '', queryString) || PinyinMatch.match(item.deptName || '', queryString)))
    } else {
      cb(searchUserList)
    }
  } else {
    const request = getSearchRequest()
    let params = {pageType: 0}

    request(params).then(res => {
      const resData = res.data.data
      optionData.searchUserList = resData.hasOwnProperty('list') ? (resData.list || []) : (resData || [])
      if (queryString) {
        cb(optionData.searchUserList.filter(item => PinyinMatch.match(item[userConfig.value.label] || '', queryString)))
      } else {
        cb(optionData.searchUserList)
      }
    }).catch(() => {
    })
  }
}

/**
 * 获取搜索请求
 * 根据列表请求对应获取，如果 props searchParams 有值，以 searchParams 为准
 */
function getSearchRequest() {
  // 人资的默认搜索接口
  if (config.value.dataType === 'hrm') {
    return hrmEmployeeQueryInAPI
  }

  return userListAPI
}

/**
 * 搜索选择
 */
function searchSelect(item) {
  // todo whf 这里的userCheckBox组件，没有找到
  this.$refs.userCheckbox.searchSelect(item)
}

/**
 * 部门 change
 */
function depCheckboxChange(val) {
  if (config.value.selectType === 'user') {
    return
  }
  if (properties.radio) {
    if (optionData.userDataValue && optionData.userDataValue.length > 0) {
      optionData.userDataValue = []
      if (!config.value.showSureBtn) {
        emits('update:userValue', [])
      }
    }
    // 单选直接关闭窗口
    emits('close')
  }
  if (!config.value.showSureBtn) {
    emits('update:depValue', val)
    nextTick(() => {
      emits('depChange', val)
      emits('change', optionData.userDataValue, val, 'dep')
    })
  }
}

/**
 * user change
 */
function userCheckboxChange(val) {
  if (config.value.selectType === 'dep') {
    return
  }
  if (properties.radio) {
    if (optionData.depDataValue && optionData.depDataValue.length > 0) {
      optionData.depDataValue = []
      if (!config.value.showSureBtn) {
        emits('update:depValue', [])
      }
    }
    // 单选直接关闭窗口
    emits('close')
  }
  if (!config.value.showSureBtn) {
    emits('update:userValue', val)
    nextTick(() => {
      emits('userChange', val)
      emits('change', val, optionData.depDataValue, 'user')
    })
  }
}

/**
 * 全部勾选
 */
function handleCheckAllChange(val) {
  if (userCheckboxRef.value) {
    userCheckboxRef.value.handleCheckAllChange(val)
  }
  if (depCheckboxRef.value) {
    depCheckboxRef.value.handleCheckAllChange(val)
  }
}

/**
 * 用户全选
 */
function userAllSelect(allChecked) {
  optionData.userAllChecked = allChecked
  if ((optionData.depAllChecked || !optionData.currentBreadcrumbItem.deptList || optionData.currentBreadcrumbItem.deptList.length === 0 || config.value.selectType === 'user') && optionData.userAllChecked) {
    optionData.allChecked = true
  } else {
    optionData.allChecked = false
  }
}

/**
 * 部门全选
 */
function depAllSelect(allChecked) {
  optionData.depAllChecked = allChecked
  if (optionData.depAllChecked && (optionData.userAllChecked || !optionData.currentBreadcrumbItem.employeeList || optionData.currentBreadcrumbItem.employeeList.length === 0 || config.value.selectType === 'dep')) {
    optionData.allChecked = true
  } else {
    optionData.allChecked = false
  }
}

/**
 * 清空全部
 */
function clearAll() {
  if (config.value.showSureBtn) {
    optionData.depDataValue = []
    optionData.userDataValue = []
  } else {
    emits('update:depValue', [])
    emits('update:userValue', [])
    emits('depChange', [])
    emits('userChange', [])
  }
}

/**
 * 确定点击
 */
function sureClick() {
  emits('update:depValue', optionData.depDataValue)
  emits('update:userValue', optionData.userDataValue)
  emits('depChange', optionData.depDataValue)
  emits('userChange', optionData.userDataValue)
  emits('change', optionData.userDataValue, optionData.userDataValue)
  emits('close')
}

/**
 * 获取部门员工数据
 */
function getDepUserList(deptId, depInfo) {
  optionData.loading = true
  const request = config.value.dataType === 'hrm' ? hrmEmployeeQueryByDeptAPI : (adminUserQueryByDeptAPI)
  request(deptId).then(res => {
    const data = res.data || {}
    const deptList = data.deptList || []

    // employeeList 人资  userList 系统管理
    const employeeList = data.employeeList || data.userList || []
    if (deptId == 0) {
      optionData.breadcrumbList = [{label: '全部', deptList: deptList, employeeList: employeeList}]
    } else {
      optionData.breadcrumbList.push({label: depInfo.name, deptList: deptList, employeeList: employeeList})
    }
    optionData.loading = false
  }).catch(() => {
    optionData.loading = false
  })
}

/**
 * 下一级
 */
function nextClick(item) {
  getDepUserList(item.deptId, item)
}


/**
 * 面包屑点击
 */
function breadcrumbBtn(item, index) {
  if (index + 1 <= optionData.breadcrumbList.length - 1) {
    optionData.breadcrumbList.splice(index + 1, optionData.breadcrumbList.length - 1)
  }
}


</script>

<style lang="scss" scoped>
/* 选择员工 */

.search-list {
  padding: 5px 0;
  height: 248px;
  overflow: auto;
}

.xh-user {
  color: #333;
  font-size: 13px;

  &__hd {
    padding: 0 15px;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid $xr-border-line-color;
  }

  &__bd {
    padding: 10px 12px;
  }

  &__ft {
    padding: 5px 12px;
    background: #f7f8fa;
    border-top: 1px solid $xr-border-line-color;

    .el-button {
      font-size: 12px;
    }
  }

  &__list {
    height: calc(100% - 24px);
    overflow-y: auto;
    padding-left: 5px;
  }
}

// 选择信息
.select-info {
  display: inline-block;
  width: calc(100% - 30px);

  &--num {
    color: $xr-color-primary;
  }
}

// check样式
.el-checkbox-group {
  overflow-x: hidden;
}

.el-checkbox {
  :deep( .el-checkbox__label) {
    color: #333;
  }
}

.all-check {
  display: inline-block;
  padding: 5px 0;
}

.el-autocomplete {
  width: 100%;

  :deep( .el-input__inner) {
    background-color: #F4F4F4;
    border: none;
  }
}

:deep( .wk-dep-checkbox) {
  &.is-select-user {
    .el-checkbox__input {
      display: none;
    }

    .el-checkbox__label {
      padding-left: 0;
    }
  }
}
</style>
